package com.itheima.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.itheima.reggie.common.R;
import com.itheima.reggie.common.UserHolder;
import com.itheima.reggie.entify.Employee;
import com.itheima.reggie.entify.User;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter("/*")
@Component
public class LoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //需要放行的路径
        String[] loginUrls = {
                "/user/login",
                "/user/sendMsg",
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**"};
        AntPathMatcher antPathMatcher = new AntPathMatcher();
        HttpServletRequest request = (HttpServletRequest) servletRequest;

        String requestURI = request.getRequestURI();
        for (String loginUrl : loginUrls) {
            boolean match = antPathMatcher.match(loginUrl, requestURI);
            if (match) {
                filterChain.doFilter(servletRequest, servletResponse);
                return;
            }
        }
        HttpSession session = request.getSession();
        Employee loginEmployee = (Employee) session.getAttribute("loginEmployee");
        User loginUser = (User) session.getAttribute("loginUser");
        if (loginEmployee != null || loginUser != null) {
            //登录成功,向ThreadLocal存入当前用户的id
            if(loginEmployee!=null){
                Long id = loginEmployee.getId();
                UserHolder.setUserId(id);
            }
            if(loginUser!=null){
                Long id = loginUser.getId();
                UserHolder.setUserId(id);
            }
            //放行
            filterChain.doFilter(servletRequest, servletResponse);
            //回去的代码，需要释放ThreadLocal中存储的用户id，防止内存溢出
            UserHolder.release();
        } else {//未登录
            HttpServletResponse response = (HttpServletResponse) servletResponse;
            R<Object> notlogin = R.error("NOTLOGIN");
            String jsonString = JSON.toJSONString(notlogin);
            response.getWriter().write(jsonString);
        }
    }

    @Override
    public void destroy() {
    }
}
